<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus05.html">Previous Chapter</a>
    <li> <a href="cplusplus07.html">Next Chapter</a>
</ul>
<hr>
<a name="Classes"></a><a name="l93"></a>
<h1>Chapter 6: Classes</h1>
<a name="classes"></a>
<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="classes/intro"></a>In this chapter classes are formally introduced. Two special member
functions, the constructor and the destructor, are presented.
<p>
In steps we will construct a class <code>Person</code>, which could be used in a
database application to store a person's name, address and phone number.
<p>
<a name="PERSON"></a> Let's start by creating the declaration of a <code>class
Person</code> right away. The class declaration is normally contained in the
<em>header file</em> of the class, e.g., <code>person.h</code>. A class declaration is
generally not called a <em>declaration</em>, though. Rather, the common name for
class declarations is <a name="an855"></a>
<em>class interface</em>, to be distinguished from the
definitions of the function members, called the
    <a name="an856"></a>
<em>class implementation</em>. Thus, the interface of the <code>class Person</code>
is given next:
    <pre>
    #include &lt;string&gt;

    class Person
    {
        std::string d_name;     // name of person
        std::string d_address;  // address field
        std::string d_phone;    // telephone number
        size_t    d_weight;   // the weight in kg.

        public:                 // interface functions
            void setName(std::string const &amp;n);
            void setAddress(std::string const &amp;a);
            void setPhone(std::string const &amp;p);
            void setWeight(size_t weight);

            std::string const &amp;name()    const;
            std::string const &amp;address() const;
            std::string const &amp;phone()   const;
            size_t weight()            const;
    };
</pre>
    It should be noted that this terminology is frequently loosely applied.
Sometimes, <em>class definition</em> is used to indicate the class interface. While
the class <em>definition</em> (so, the <em>interface</em>) contains the <em>declarations</em>
of its members, the actual <em>implementation</em> of these members is also
referred to as the <em>definition</em> of these members. As long as the concept of
the class <em>interface</em> and the class <em>implementation</em> is well
distinguished, it should be clear from the context what is meant by a
`definition'.
<p>
The data fields in this class are <code>d_name, d_address, d_phone</code> and
<code>d_weight</code>. All fields except <code>d_weight</code> are <code>string</code> objects. As the
data fields are not given a specific <a name="an857"></a>
<em>access modifier</em>, they are
<a name="an858"></a>
<code>private</code>, which means that they can only be accessed by the functions
of the class <code>Person</code>. Alternatively, the label `<code>private:</code>' might have
been used at the beginning of a private section of the class definition.
<p>
The data are manipulated by interface functions which take care of all
communication with code outside of the class. Either to set the data fields
to a given value (e.g., <code>setName()</code>) or to inspect the data (e.g.,
<code>name()</code>). Functions merely returning values stored inside the object, not
allowing the caller to modify these internally stored values, are called
<a name="an859"></a>
<em>accessor functions</em>.
<p>
Note once again how similar the <code>class</code> is to the <a name="an860"></a>
<code>struct</code>. The
fundamental difference being that by default classes have <em>private</em> members,
whereas structs have <a name="an861"></a>
<em>public</em> members. Since the convention calls for the
public members of a class to appear first, the keyword <code>private</code> is needed
to switch back from public members to the (default) private situation.
<p>
A few remarks concerning <em>style</em>. Following <em>Lakos</em> (Lakos, J., 2001)
    <a name="an862"></a>
 <strong>Large-Scale C++ Software Design</strong> (Addison-Wesley). I
suggest the following setup of class interfaces:
    <ul>
    <li> All data members should have <em>private access rights</em>, and should be
placed at the head of the interface.
    <li> All data members start with <code>d_</code>, followed by a name suggesting the
meaning of the variable (In chapter <a href="cplusplus10.html#StaticDataFun">10</a> we'll also
encounter data members starting with <code>s_</code>).
    <li> Non-private data members <em>do</em> exist, but one should be hesitant to
use non-private access rights for data members (see also chapter
<a href="cplusplus13.html#INHERITANCE">13</a>).
    <li> Two broad classes of member functions are <a name="an863"></a>
<em>manipulators</em> and
<a name="an864"></a>
<em>accessor functions</em>. <em>Manipulators</em> allow the users of objects to
actually modify the internal data of the objects. By convention, manipulators
start with <code>set</code>. E.g., <code>setName()</code>.
    <li> With <em>accessors</em>, often a <code>get</code>-prefix is encountered, e.g.,
<code>getName()</code>. However, following the conventions used in the
<a name="an865"></a>
<strong>Qt</strong> <a name="an866"></a>
<em>Graphical User Interface Toolkit</em> (see
<a name="an867"></a>
<code>http://www.trolltech.com</code>), the <code>get</code>-prefix is <em>dropped</em>. So, rather
than defining the member <code>getAddress()</code>, the function will simply be defined
as <code>address()</code>.
    </ul>
    Style conventions usually take a long time to develop. There is nothing
obligatory about them, however. I suggest that readers who have compelling
reasons <em>not</em> to follow the above style conventions use their own. All
others should adopt the above style conventions.
<p>
<a name="l94"></a>
<h2>6.1: The constructor</h2>
    <a name="classes/construc"></a>A class in <strong>C++</strong> may contain two special categories of member functions
which are involved in the internal workings of the class. These member
function categories are, on the one hand, the constructors and, on the other
hand, the <a name="an868"></a>
destructor. The <em>destructor</em>'s primary task is to return memory
allocated by an object to the common pool when an object goes `out of scope'.
Allocation of memory is discussed in chapter <a href="cplusplus07.html#MEMORY">7</a>, and
destructors will therefore be discussed in depth in that chapter.
<p>
In this chapter the emphasis will be on the basic form of the <code>class</code> and
on its <a name="an869"></a>
 constructors.
<p>
The constructor has by definition the same name as its class. The constructor
does not specify a return value, not even <code>void</code>.  E.g., for the class
<code>Person</code> the constructor is <code>Person::Person()</code>. The <strong>C++</strong> run-time
system ensures that the constructor of a class, if defined, is called when a
variable of the class, called an <a name="an870"></a>
object, is defined (`created'). It is of
course possible to define a class with no constructor at all. In that case the
program will call a default constructor when a corresponding object is
created. What actually happens in that case depends on the way the class has
been defined. The actions of the default constructors are covered in section
<a href="cplusplus06.html#MemberInitializers">6.4.1</a>.
<p>
Objects may be defined locally or globally. However, in <strong>C++</strong> most objects
are defined locally. Globally defined objects are hardly ever required.
<p>
When an <a name="an871"></a>
 object is defined locally (in a function), the
constructor is called every time the function is called. The object's
constructor is then activated at the point where the object is defined (a
subtlety here is that a variable may be defined implicitly as, e.g., a
temporary variable in an expression).
<p>
When an object is defined as a static object <a name="an872"></a>
 (i.e., it is
static variable) in a function, the constructor is called when the function in
which the static variable is defined is called for the first time.
<p>
When an object is defined as a <a name="an873"></a>
global object the constructor is called when
the program starts. Note that in this case the constructor is called even
before the function <code>main()</code> is started.  This feature is illustrated in the
following program:
    <pre>
    #include &lt;iostream&gt;
    using namespace std;

    class Demo
    {
        public:
            Demo();
    };

    Demo::Demo()
    {
        cout &lt;&lt; "Demo constructor called\n";
    }

    Demo d;

    int main()
    {}

    /*
        Generated output:
    Demo constructor called
    */
</pre>
        The above listing shows how a class <code>Demo</code> is defined which consists
of just one function: the constructor. The constructor performs but one
action: a message is printed. The program contains one global object of the
class <code>Demo</code>, and <code>main()</code> has an empty body. Nonetheless, the program
produces some output.
<p>
Some important characteristics of constructors are:
    <ul>
    <li> The constructor has the same name as its class.
    <li> The <a name="an874"></a>
 primary function of a
constructor is to make sure that all its data members have sensible or at
least defined values once the object has been constructed. We'll get back to
this important task shortly.
    <li> The constructor does not have a return value. This holds
true for the declaration of the constructor in the class definition, as
in:
    <pre>
        class Demo
        {
            public:
                Demo();         // no return value here
        };
</pre>
    and it holds true for the definition of the constructor function, as
in:
    <pre>
        Demo::Demo()            // no return value here
        {
            // statements ...
        }
</pre>
    <li> The constructor function in the example above has no arguments. It is
called the <a name="an875"></a>
<em>default constructor</em>.  That a constructor has no arguments is,
however, no requirement <em>per se</em>. We shall shortly see that it is possible
to define constructors <em>with</em> arguments as well as <em>without</em>
arguments.
<p>
<li> <strong>NOTE:</strong> <em>Once a constructor is defined having arguments, the
default constructor doesn't exist anymore, unless the default constructor is
defined explicitly too.</em>
<p>
This has important consequences, as the default constructor is required in
cases where it must be able to construct an object either <em>with</em> or
<em>without</em> explicit initialization values. By merely defining a constructor
having at least one argument, the implicitly available default constructor
disappears from view. As noted, to make it available again in this situation,
it must be defined explicitly too.
    </ul>
<p>
<a name="l95"></a>
<h3>6.1.1: A first application</h3>
        <a name="classes/application"></a>As illustrated at the beginning of this chapter, the class <code>Person</code> contains
three <code>private</code> <code>string</code> data members and an <code>size_t d_weight</code> data
member. These data members can be manipulated by the
    <a name="an876"></a>
interface functions.
<p>
Classes (should) operate as follows:
    <ul>
    <li> When the object is constructed, its data members are given `sensible'
values. Thus, objects never suffer from uninitialized values.
    <li> The assignment to a data member (using a
<code>set...()</code> function) consists of the assignment of the new value to the
corresponding data member. This assignment is fully controlled by the
class-designer. Consequently, the object itself is `responsible' for its own
data-integrity.
    <li> Inspecting data members using the accessor functions simply returns
the value of the requested data member. Again, this will not result in
uncontrolled modifications of the object's data.
    </ul>
    The <code>set...()</code> functions could be constructed as follows:
    <pre>
    #include "person.h"                 // given earlier

    // interface functions set...()
    void Person::setName(string const &amp;name)
    {
        d_name = name;
    }

    void Person::setAddress(string const &amp;address)
    {
        d_address = address;
    }

    void Person::setPhone(string const &amp;phone)
    {
        d_phone = phone;
    }

    void Person::setWeight(size_t weight)
    {
        d_weight = weight;
    }
</pre>
<p>
Next the <a name="an877"></a>
accessor functions are defined.  Note the occurence of the
keyword <code>const</code> following the parameter lists of these functions: these
member functions are called <a name="an878"></a>
<em>const member functions</em>, indicating that
they will not modify their <em>object</em>'s data when they're called. Furthermore,
notice that the return types of the member functions returning the values of
the <code>string</code> data members are <code>string const &amp;</code> types: the <code>const</code> here
indicates that the <em>caller</em> of the member function <em>cannot</em> alter the
returned value itself. The caller of the accessor member function <em>could</em>
copy the returned value to a variable of its own, though, and <em>that</em>
variable's value may then of course be modified <em>ad lib</em>.  Const member
functions are discussed in greater detail in section <a href="cplusplus06.html#ConstFunctions">6.2</a>. The
return value of the <code>weight()</code> member function, however, is a plain
<code>size_t</code>, as this can be a simple copy of the value that's stored in the
<code>Person</code>'s <code>weight</code> member:
    <pre>
    #include "person.h"                 // given earlier

    // accessor functions ...()
    string const &amp;Person::name() const
    {
        return d_name;
    }

    string const &amp;Person::address() const
    {
       return d_address;
    }

    string const &amp;Person::phone() const
    {
       return d_phone;
    }

    size_t Person::weight() const
    {
       return d_weight;
    }
</pre>
<p>
The class definition of the <code>Person</code> class given earlier can still be
used. The <code>set...()</code> and accessor functions merely implement the member
functions declared in that class definition.
<p>
The following example shows the use of the class <code>Person</code>. An object is
initialized and passed to a function <code>printperson()</code>, which prints the
person's data. Note also the usage of the <a name="an879"></a>
reference operator <code>&amp;</code> in the
argument list of the function <code>printperson()</code>. This way only a reference to
an existing <code>Person</code> object is passed, rather than a whole object.  The fact
that <code>printperson()</code> does not modify its argument is evident from the fact
that the parameter is declared <code>const</code>.
<p>
Alternatively, the function <code>printperson()</code> might have been defined
as a <code>public</code> member function of the class <code>Person</code>, rather than a plain,
objectless function.
    <pre>
    #include &lt;iostream&gt;
    #include "person.h"                 // given earlier

    void printperson(Person const &amp;p)
    {
        cout &lt;&lt; "Name    : " &lt;&lt; p.name()     &lt;&lt; endl &lt;&lt;
                "Address : " &lt;&lt; p.address()  &lt;&lt; endl &lt;&lt;
                "Phone   : " &lt;&lt; p.phone()    &lt;&lt; endl &lt;&lt;
                "Weight  : " &lt;&lt; p.weight()   &lt;&lt; endl;
    }

    int main()
    {
        Person p;

        p.setName("Linus Torvalds");
        p.setAddress("E-mail: Torvalds@cs.helsinki.fi");
        p.setPhone(" - not sure - ");
        p.setWeight(75);           // kg.

        printperson(p);
        return 0;
    }
/*
    Produced output:

Name    : Linus Torvalds
Address : E-mail: Torvalds@cs.helsinki.fi
Phone   :  - not sure -
Weight  : 75

*/
</pre>
<p>
<a name="l96"></a>
<h3>6.1.2: Constructors: with and  without arguments</h3>
        <a name="classes/arguments"></a>In the above declaration of the class <code>Person</code> the constructor has no
arguments. <strong>C++</strong> allows constructors to be defined with or without argument
lists. The arguments are supplied when an object is created.
<p>
For the class <code>Person</code> a constructor expecting three strings and an size_t
may be handy: these arguments then represent, respectively, the person's name,
address, phone number and weight. Such a constructor is:
        <pre>
    Person::Person(string const &amp;name, string const &amp;address,
                    string const &amp;phone, size_t weight)
    {
        d_name = name;
        d_address = address;
        d_phone = phone;
        d_weight = weight;
    }
</pre>
    The constructor must also be declared in the class interface:
        <pre>
    class Person
    {
        public:
            Person(std::string const &amp;name, std::string const &amp;address,
                   std::string const &amp;phone, size_t weight);

            // rest of the class interface
    };
</pre>
    However, now that this constructor has been declared, the default
constructor must be declared explicitly too, if we still want to be able to
construct a plain <code>Person</code> object without any specific initial
values for its data members.
<p>
Since <strong>C++</strong> allows function overloading, such a declaration of a
constructor can co-exist with a constructor without arguments. The class
<code>Person</code> would thus have two constructors, and the relevant part of the
class interface becomes:
        <pre>
    class Person
    {
        public:
            Person();
            Person(std::string const &amp;name, std::string const &amp;address,
                   std::string const &amp;phone, size_t weight);

            // rest of the class interface
    };
</pre>
    In this case, the <code>Person()</code> constructor doesn't have to do much, as it
doesn't have to initialize the <code>string</code> data members of the <code>Person</code>
object: as these data members themselves are objects, they are already
initialized to empty strings by <a name="an880"></a>
 default.  However,
there is also an <code>size_t</code> data member. That member is a variable of a
basic type and basic type variabes are not initialized automatically.  So,
unless the value of the <code>d_weight</code> data member is explicitly initialized, it
will be
    <ul>
    <li> A <em>random</em> value for local <code>Person</code> objects,
    <li> 0 for global and static <code>Person</code> objects
    </ul>
    The 0-value might not be too bad, but normally we don't want a <em>random</em>
value for our data members. So, the default constructor has a job to do:
initializing the data members which are not initialized to sensible values
automatically. Here is an implementation of the default constructor:
        <pre>
    Person::Person()
    {
        d_weight = 0;
    }
</pre>
    The use of a constructor with and without arguments (i.e., the default
constructor) is illustrated in the following code fragment. The object <code>a</code>
is initialized at its definition using the constructor with arguments, with
the <code>b</code> object the default constructor is used:
        <pre>
    int main()
    {
        Person a("Karel", "Rietveldlaan 37", "542 6044", 70);
        Person b;

        return 0;
    }
</pre>
    In this example, the <code>Person</code> objects <code>a</code> and <code>b</code> are created when
<code>main()</code> is started: they are <em>local</em> objects, living for as long as the
<code>main()</code> function is active.
<p>
If <code>Person</code> objects must be contructed using other arguments, other
constructors are required as well. It is also possible to define default
parameter values. These <a name="an881"></a>
default parameter values must be given in the class
interface, e.g.,
        <pre>
    class Person
    {
        public:
            Person();
            Person(std::string const &amp;name,
                   std::string const &amp;address = "--unknown--",
                   std::string const &amp;phone   = "--unknown--",
                   size_t weight = 0);

            // rest of the class interface
    };
</pre>
<p>
Often, the constructors are implemented highly similar. This results from
the fact that often the constructor's parameters are defined for convenience:
a constructor not requiring a <code>phone</code> number but requiring a <code>weight</code>
cannot be defined using default arguments, since only the last but one
parameter in the constructor defining all four parameters is not
required. This cannot be solved using default argument values, but only by
defining another constructor, not requiring <code>phone</code> to be specified.
<p>
Although some languages (e.g., <strong>Java</strong>) allow constructors to call
constructors, this is conceptually weird. It's weird because it makes a kludge
out of the constructor concept. A constructor is meant to construct an object,
not to construct itself while it hasn't been constructed yet.
<p>
In <strong>C++</strong> the way to proceed is as follows: All constructors <em>must</em>
initialize their reference data members, or the compiler will (rightfully)
complain. This is one of the fundamental reasons why you can't call a
constructor during a construction. Next, we have two options:
    <ul>
    <li> If the body of your construction process is extensive, but
(parameterizable) identical to another constructor's body, factorize! Make a
private member <code>init(maybe having params)</code> called by the constructors. Each
constructor furthermore initializes any reference data members its class may
have.
    <li> If the constructors act fundamentally differently, then there's
nothing left but to construct completely different constructors.
    </ul>
<p>
<a name="l97"></a>
<strong>6.1.2.1: The order of construction</strong>
            <a name="classes/order"></a>The possibility to pass arguments to constructors allows us to monitor the
construction of objects during a program's execution.  This is shown in the
next listing, using a class <code>Test</code>. The program listing below shows a class
<code>Test</code>, a global <code>Test</code> object, and two local <code>Test</code> objects: in a
function <code>func()</code> and in the <code>main()</code> function. The order of construction
is as expected: first global, then main's first local object, then
<code>func()</code>'s local object, and then, finally, <code>main()</code>'s second local
object:
    <pre>
    #include &lt;iostream&gt;
    #include &lt;string&gt;
    using namespace std;

    class Test
    {
        public:
            Test(string const &amp;name);   // constructor with an argument
    };

    Test::Test(string const &amp;name)
    {
        cout &lt;&lt; "Test object " &lt;&lt; name &lt;&lt; " created" &lt;&lt; endl;
    }

    Test globaltest("global");

    void func()
    {
        Test functest("func");
    }

    int main()
    {
        Test first("main first");
        func();
        Test second("main second");
        return 0;
    }
/*
    Generated output:
Test object global created
Test object main first created
Test object func created
Test object main second created
*/
</pre>
<p>
<a name="ConstFunctions"></a><a name="l98"></a>
<h2>6.2: Const member functions and const objects</h2>
    <a name="classes/member"></a>The keyword <code>const</code> is often used behind the parameter list of
member functions. This keyword indicates that a member
function does not alter the data members of its object, but will only inspect
them. These member functions are called <a name="an882"></a>
<em>const member functions</em>.
Using the example of the class <code>Person</code>, we see that the accessor
functions were declared <code>const</code>:
        <pre>
    class Person
    {
        public:
            std::string const &amp;name() const;
            std::string const &amp;address() const;
            std::string const &amp;phone() const;
    };
</pre>
    This fragment illustrates that the keyword <code>const</code> appears
<em>behind</em> the functions' argument lists. Note that in this situation the
rule of thumb given in section <a href="cplusplus03.html#ConstRule">3.1.3</a> applies as well: whichever
appears <strong>before</strong> the keyword <code>const</code>, may not be altered and doesn't alter
(its own) data.
<p>
The <code>const</code> specification must be repeated in the definitions of member
functions:
        <pre>
    string const &amp;Person::name() const
    {
        return d_name;
    }
</pre>
    A member function which is declared and defined as <code>const</code> may not alter
any data fields of its class. In other words, a statement like
        <pre>
    d_name = 0;
</pre>
    in the above <code>const</code> function <code>name()</code> would result in a
compilation error.
<p>
<code>Const</code> member functions exist because <strong>C++</strong> allows <code>const</code> objects to
be created, or (used more often) references to <code>const</code> objects to be passed
to functions. For such objects only member functions which do not modify it,
i.e., the <code>const</code> member functions, may be called. The only exception to
this rule are the constructors and destructor: these are called
`automatically'. The possibility of calling constructors or destructors is
comparable to the definition of a variable <code>int const max = 10</code>. In
situations like these, no <em>assignment</em> but rather an <em>initialization</em>
takes place at creation-time.  Analogously, the constructor
        <a name="an883"></a>

    can <strong>initialize</strong> its object when the <code>const</code> variable is created, but
subsequent assignments cannot take place.
<p>
The following example shows the definition of a <code>const</code> object of the class
<code>Person</code>. When the object is created the data fields are initialized by the
constructor:
        <pre>
    Person const me("Karel", "karel@icce.rug.nl", "542 6044");
</pre>
<p>
Following this definition it would be illegal to try to redefine the name,
address or phone number for the object <code>me</code>: a statement as
        <pre>
    me.setName("Lerak");
</pre>
    would not be accepted by the compiler. Once more, look at the position of
the <code>const</code> keyword in the variable definition: <code>const</code>, following
<code>Person</code> and preceding <code>me</code> associates to the left: the <code>Person</code> object
in general must remain unaltered. Hence, if multiple objects were defined
here, both would be constant <code>Person</code> objects, as in:
        <pre>
    Person const        // all constant Person objects
        kk("Karel", "karel@icce.rug.nl", "542 6044"),
        fbb("Frank", "f.b.brokken@rug.nl", "363 9281");
</pre>
<p>
Member functions which do not modify their object should be defined as
<code>const</code> member functions.  This subsequently allows the use of these
functions with <code>const</code> objects or with <code>const</code> references. As a
    <a name="an884"></a>
rule of thumb it is stated here that member functions should always be
given the <code>const</code> attribute, unless they actually modify the object's data.
<p>
Earlier, in section <a href="cplusplus02.html#FunctionOverloading">2.5.11</a> the concept of function
overloading was introduced. There it noted that member functions may
    <a name="an885"></a>

be overloaded merely by their <code>const</code> attribute. In those cases, the
compiler will use the member function matching most closely the
const-qualification of the object:
    <ul>
    <li> When the object is a <code>const</code> object, only <code>const</code> member
functions can be used.
    <li> When the object is not a <code>const</code> object, non-<code>const</code> member
functions will be used, <em>unless</em> only a <code>const</code> member function is
available. In that case, the <code>const</code> member function will be used.
    </ul>
    An example showing the selection of (non) <code>const</code> member functions is
given in the following example:
        <pre>
    #include &lt;iostream&gt;
    using namespace std;

    class X
    {
        public:
            X();
            void member();
            void member() const;
    };

    X::X()
    {}
    void X::member()
    {
        cout &lt;&lt; "non const member\n";
    }
    void X::member() const
    {
        cout &lt;&lt; "const member\n";
    }

    int main()
    {
        X const constObject;
        X       nonConstObject;

        constObject.member();
        nonConstObject.member();
    }
    /*
            Generated output:

        const member
        non const member
    */
</pre>
    Overloading member functions by their <code>const</code> attribute commonly occurs
in the context of <em>operator overloading</em>. See chapter
<a href="cplusplus09.html#OperatorOverloading">9</a>, in particular section <a href="cplusplus09.html#OPERATORINDEX">9.1</a> for
details.
<p>
<a name="ANONYMOUS"></a><a name="l99"></a>
<h3>6.2.1: Anonymous objects</h3>
        <a name="classes/anonymous"></a>Situations exists where objects are used because they offer a certain
functionality. They only exist because of the functionality they offer, and
nothing in the objects themselves is ever changed. This situation resembles
the well-known situation in the <strong>C</strong> programming language where a function
pointer is passed to another function, to allow run-time configuration of the
behavior of the latter function.
<p>
For example, the class <code>Print</code> may offer a facility to print a string,
prefixing it with a configurable prefix, and affixing a configurable affix to
it. Such a class <em>could</em> be given the following prototype:
<p>
<pre>
    class Print
    {
        public:
            printout(std::string const &amp;prefix, std::string const &amp;text,
                     std::string const &amp;affix) const;
    };
</pre>
    An interface like this would allow us to do things like:
        <pre>
    Print print;
    for (int idx = 0; idx &lt; argc; ++idx)
        print.printout("arg: ", argv[idx], "\n");
</pre>
    This would work well, but can greatly be improved if we could pass
<code>printout</code>'s invariant arguments to <code>Print</code>'s constructors: this way we
would not only simplify <code>printout</code>'s prototype (only one argument would need
to be passed rather than three, allowing us to make faster calls to
<code>printout</code>) but we could also capture the above code in a function expecting
a <code>Print</code> object:
        <pre>
    void printText(Print const &amp;print, int argc, char *argv[])
    {
        for (int idx = 0; idx &lt; argc; ++idx)
            print.printout(argv[idx]);
    }
</pre>
    Now we have a fairly generic piece of code, at least as far as <code>Print</code>
is concerned. If we would provide <code>Print</code>'s interface with the following
constructors we would be able to configure our output stream as well:
        <pre>
    Print(char const *prefix, char const *affix);
    Print(ostream &amp;out, char const *prefix, char const *affix);
</pre>
    Now <code>printText</code> could be used as follows:
        <pre>
    Print p1("arg: ", "\n");            // prints to cout
    Print p2(cerr, "err: --", "--\n");  // prints to cerr

    printText(p1, argc, argv);          // prints to cout
    printText(p2, argc, argv);          // prints to cerr
</pre>
    However, when looking closely at this example, it should be clear that
both <code>p1</code> and <code>p2</code> are only used inside the <code>printText</code>
function. Furthermore, as we can see from <code>printText</code>'s prototype,
<code>printText</code> won't modify the internal data of the <code>Print</code> object it is
using.
<p>
In situations like these it is not necessary to define objects before they
are used. Instead <em>anonymous objects</em><a name="an886"></a>
 should be
used.<a name="an887"></a>
 Using anonymous objects is indicated when:
    <ul>
    <li> A function parameter defines a <code>const</code> reference to an object;
    <li> The object is <em>only</em> needed inside the function call.
    </ul>
<p>
Anonymous objects are defined by calling a constructor without providing a
name for the constructed object. In the above example anonymous objects can be
used as follows:
        <pre>
    printText(Print("arg: ", "\n"), argc, argv);          // prints to cout
    printText(Print(cerr, "err: --", "--\n"), argc, argv);// prints to cerr
</pre>
    In this situation the <code>Print</code> objects are constructed and immediately
passed as first arguments to the <code>printText</code> functions, where they are
accessible as the function's <code>print</code> parameter. While the <code>printText</code>
function is executing they can be used, but once the function has completed,
the <code>Print</code> objects are no longer accessible.
<p>
Anonymous objects <a name="an888"></a>
 cease to
exist when the function for which they were created has terminated. In this
respect they differ from ordinary local variables whose lifetimes end by the
time the function block in which they were defined is closed.
<p>
<a name="l100"></a>
<strong>6.2.1.1: Subtleties with anonymous objects</strong>
            <a name="classes/subtleties"></a>As discussed, anonymous objects can be used to initialize function parameters
that are <code>const</code> references to objects. These objects are created just
before such a function is called, and are destroyed once the function has
terminated. This use of anonymous objects to initialize function parameters is
often seen, but <strong>C++</strong>'s grammar allows us to use anonymous objects in other
situations as well. Consider the following snippet of code:
        <pre>
    int main()
    {
        // initial statements
        Print("hello", "world");
        // later statements
    }
</pre>
    In this example the anonymous <code>Print</code> object is constructed, and is
immediately destroyed after its construction. So, following the `initial
statements' our <code>Print</code> object is constructed, then it is destroyed again,
followed by the execution of the `later statements'. This is remarkable as it
shows that the standard lifetime rules do not apply to anonymous
objects. <a name="an889"></a>
<a name="an890"></a>
 Their
lifetime is limited to the <em>statement</em>, rather than to the <em>end of the
block</em> in which they are defined.
<p>
Of course one might wonder why a plain anonymous object could ever be
considered useful. One might think of at least one situation, though. Assume
we want to put <em>markers</em> in our code producing some output when the
program's execution reaches a certain point. An object's constructor could be
implemented so as to provide that marker-functionality, thus allowing us to
put markers in our code by defining anonymous, rather than named objects.
<p>
However, <strong>C++</strong>'s grammar contains another remarkable
characteristic. Consider the next example:
        <pre>
    int main(int argc, char *argv[])
    {
        Print p("", "");                    // 1
        printText(Print(p), argc, argv);    // 2
    }
</pre>
    In this example a non-anonymous object <code>p</code> is constrcted in statement 1,
which object is then used in statement 2 to <em>initialize</em> an anonymous object
which, in turn, is then used to initialize <code>printText</code>'s <code>const</code> reference
parameter. This use of an existing object to initialize another object is
common practice, and is based on the existence of a so-called
    <a name="an891"></a>
<em>copy constructor</em>. A copy constructor creates an object (as it is a
constructor), using an existing object's characteristics to initialize the new
object's data. Copy constructors are discussed in depth in chapter
<a href="cplusplus07.html#MEMORY">7</a>, but presently merely the concept of a copy constructor is used.
<p>
In the last example a copy constructor was used to initialize an anonymous
object, which was then used to initialize a parameter of a function. However,
when we try to apply the same trick (i.e., using an existing object to
initialize an anonymous object) to a plain statement, the compiler generates
an error: the object <code>p</code> can't be redefined (in statement 3, below):
        <pre>
    int main(int argc, char *argv[])
    {
        Print p("", "");                    // 1
        printText(Print(p), argc, argv);    // 2
        Print(p);                           // 3 error!
    }
</pre>
    So, using an existing object to initialize an anonymous object
that is used as function argument is ok, but an existing object can't be used
to initialize an anonymous object in a plain statement?
<p>
The answer to this apparent contradiction is actually found in the
compiler's error message itself. At statement 3 the compiler states something
like:
        <pre>
    error: redeclaration of 'Print p'
</pre>
    which solves the problem, by realizing that within a compound statement
objects and variables may be defined as well. Inside a compound statement,
a <em>type name</em> followed by a <code>variable name</code> is the grammatical form of a
variable definition. <em>Parentheses</em> can be used to break priorities, but if
there are no priorities to break, they have no effect, and are simply ignored
by the compiler. In statement 3 the parentheses allowed us to get rid of the
blank that's required between a type name and the variable name, but to the
compiler we wrote
        <pre>
        Print (p);
</pre>
    which is, since the parentheses are superfluous, equal to
        <pre>
        Print p;
</pre>
    thus producing <code>p</code>'s redeclaration.
<p>
As a further example: when we define a variable using a basic type (e.g.,
<code>double</code>) using superfluous parentheses the compiler will quietly remove
these parentheses for us:
        <pre>
    double ((((a))));       // weird, but ok.
</pre>
<p>
To summarize our findings about anonymous variables:
    <ul>
    <li> Anonymous objects are great for initializing <code>const</code> reference
parameters.
    <li> The same syntaxis, however, can also be used in stand-alone
statements, in which they are interpreted as variable definitions if our
intention actually was to initialize an anonymous object using an existing
object.
    <li> Since this may cause confusion, it's probably best to restrict the
use of anonymous objects to the first (and main) form: initializing function
parameters.
    </ul>
<p>
<a name="INLINE"></a><a name="l101"></a>
<h2>6.3: The keyword `inline'</h2>
    <a name="classes/inline"></a>Let us take another look at the implementation of the function
<code>Person::name()</code>:
        <pre>
    std::string const &amp;Person::name() const
    {
        return d_name;
    }
</pre>
    This function is used to retrieve the name field of an object of the class
<code>Person</code>. In a code fragment like:
        <pre>
    Person frank("Frank", "Oostumerweg 17", "403 2223");

    cout &lt;&lt; frank.name();
</pre>
    the following actions take place:
    <ul>
    <li> The function <code>Person::name()</code> is called.
    <li> This function returns the <code>name</code> of the object <code>frank</code> as a
reference.
    <li> The referenced name is inserted into <code>cout</code>.
    </ul>
<p>
Especially the first part of these actions results in some time loss, since an
extra function call is necessary to retrieve the value of the <code>name</code> field.
Sometimes a faster procedure may be desirable, in which the <code>name</code> field
becomes immediately available, without ever actually calling a function
<code>name()</code>. This can be realized using <a name="an892"></a>
<code>inline</code> functions.
<p>
<a name="DEFINLINE"></a><a name="l102"></a>
<h3>6.3.1: Defining members inline</h3>
        <a name="classes/defineinline"></a>Inline functions may be implemented <em>in the class interface itself</em>. For the
class <code>Person</code> this results in the following implementation of
<code>name()</code>:
        <pre>
    class Person
    {
        public:
            std::string const &amp;name() const
            {
                return d_name;
            }
    };
</pre>
    Note that the <a name="an893"></a>
inline code of the function <code>name()</code> now literally
occurs inline in the interface of the class <code>Person</code>. The keyword <code>const</code>
occurs after the function declaration, and before the code block.
<p>
Although members can be defined inside the class interface itself, it
should be considered bad practice because of the following considerations:
    <ul>
    <li> Defining functions inside the interface confuses the interface with
the implementation. The interface should merely document what functionality
the class offers. Mixing member declarations with implementation detail
complicates understanding the interface. Readers will have to skip over 
implementation details which takes time and makes it hard to grab the `broad
picture', and thus to understand at a glance what functionality 
the class's objects are offering.
    <li> Although members that are eligible for inline-coding should remain
inline, situations do exist where members migrate from an inline to a
non-inline definition. The in-class inline definition still needs editiing
(sometimes considerable editing) before a non-inline definition is ready to be
compiled. This additional editing is undesirable.
    </ul>
    Because of the above considerations inline members should not be defined
within the class interface. Rather, they should be defined <em>below</em> the class
interface. The  <code>name()</code> member of the <code>Person</code>
class is therefore preferably defined as follows:
        <pre>
    class Person
    {
        public:
            std::string const &amp;name() const;
    };

    inline std::string const &amp;Person::name() const
    {
        return d_name;
    }
</pre>
    This version of the <code>Person</code> class clearly shows that:
    <ul>
    <li> the class interface itself only contains a declaration
    <li> the inline implementation can easily be redefined as  a non-inline
implementation by removing the <code>inline</code> keyword and including the
appropriate class-header file. E.g.,
        <pre>
    #include "person.h"

    std::string const &amp;Person::name() const
    {
        return d_name;
    }
</pre>
    </ul>
Defining members inline has the following effect: Whenever an inline function
is called in a program statement, the compiler may <em>insert the function's
body</em> at the location of the function call. The function itself
may never actually be called. Consequently, the function call is prevented,
but the function's body appears as often in the final program as the inline
function is actually called.
<p>
This construction, where the function code itself is inserted rather than a
call to the function, is called an <a name="an894"></a>
inline function.  Note that using inline
functions may result in multiple occurrences of the code of those functions in
a program: one copy for each invocation of the inline function. This is
probably ok if the function is a small one, and needs to be executed
fast. It's not so desirable if the code of the function is extensive. The
compiler knows this too, and considers the
    <a name="an895"></a>
use of inline functions a <em>request</em> rather than a <em>command</em>: if the
compiler considers the function too long, it will not grant the request, but
will, instead, treat the function as a normal function. As a 
    <a name="an896"></a>
rule of thumb: members should only be defined inline if they are small
(containing a single, small statement) and if it is highly unlikely that their
definition will ever change.
<p>
<a name="l103"></a>
<h3>6.3.2: When to use inline functions</h3>
        <a name="classes/when2use"></a>When should <code>inline</code> <a name="an897"></a>
 functions be used, and when
not? There are some <a name="an898"></a>
 rules of thumb which may be followed:
    <ul>
    <li> In general <code>inline</code> functions should <strong>not</strong> be used.
<em>Voil&agrave;</em>; that's simple, isn't it?
    <li> Defining <code>inline</code> functions can be considered once a fully
developed and tested program runs too slowly and shows `bottlenecks' in
certain functions. A <a name="an899"></a>
profiler, which runs a program and determines where
most of the time is spent, is necessary to perform for such optimizations.
    <li><code>inline</code> functions can be used when member functions consist of one
very simple statement (such as the return statement in the function
<code>Person::name()</code>).
    <li> By defining a function as <code>inline</code>, its implementation is inserted
in the code wherever the function is used. As a consequence, when the
<em>implementation</em> of the inline function changes, all sources using the
inline function must be recompiled. In practice that means that all functions
must be recompiled that include (either directly or indirectly) the header
file of the class in which the inline function is defined.
    <li> It is only useful to implement an <code>inline</code> function when the time
spent during a function call is long compared to the code in the
function. An example of an  <code>inline</code> function which will hardly have any
effect on the program's speed is:
        <pre>
    void Person::printname() const
    {
        cout &lt;&lt; d_name &lt;&lt; endl;
    }
</pre>
    This function, which is, for the sake of the example, presented as a
    member of the class <code>Person</code>, contains only one statement.  However, the
statement takes a relatively long time to execute. In general, functions which
perform input and output take lots of time. The effect of the conversion of
this function <code>printname()</code> to <code>inline</code> would therefore lead to an
insignificant gain in execution time.
    </ul>
    All <code>inline</code> functions <a name="an900"></a>
 have one disadvantage:
the actual code is inserted by the compiler and must therefore be known
compile-time. Therefore, as mentioned earlier, an <code>inline</code> function can
never be located in a run-time library. Practically this means that an
<code>inline</code> function is <a name="an901"></a>
 placed near the
interface of a class, usually in the same header file. The result is a header
file which not only shows the <strong>declaration</strong> of a class, but also part of its
<strong>implementation</strong>, thus blurring the distinction between interface and
implementation.
<p>
Finally, note once again that the keyword <code>inline</code> is not really a
<em>command</em> to the compiler. Rather, it is a <em>request</em> the compiler may
or may not grant.
<p>
<a name="Composition"></a><a name="l104"></a>
<h2>6.4: Objects inside objects: composition</h2>
    <a name="classes/composition"></a>Often <a name="an902"></a>
 objects are used as data members in class
definitions. This is called <a name="an903"></a>
<em>composition</em>.
<p>
For example, the class <code>Person</code> holds information about the name,
address and phone number. This information is stored in <code>string</code> data
members, which are themselves objects: composition.
<p>
Composition is not extraordinary or <strong>C++</strong> specific: in <strong>C</strong>
a <code>struct</code> or <code>union</code> field is commonly used in other compound types.
<p>
The initialization of composed objects deserves some special attention: the
topics of the coming sections.
<p>
<a name="MemberInitializers"></a><a name="l105"></a>
<h3>6.4.1: Composition and const objects: const member initializers</h3>
        <a name="classes/comconst"></a>Composition of objects has an important consequence for the
constructor functions of the `composed' (embedded) object. Unless explicitly
instructed otherwise, the compiler generates code to call the
    <a name="an904"></a>
 default constructors of all composed classes in
the constructor of the composing class.
<p>
Often it is desirable to initialize a composed object from a specific
constructor of the composing class. This is illustrated below for the
class <code>Person</code>. In this fragment it assumed that a constructor
for a <code>Person</code> should be defined expecting four arguments: the name, address
and phone number plus the person's weight:
        <pre>
    Person::Person(char const *name, char const *address,
                    char const *phone, size_t weight)
    :
        d_name(name),
        d_address(address),
        d_phone(phone),
        d_weight(weight)
    {}
</pre>
    Following the argument list of the constructor <code>Person::Person()</code>, the
constructors of the <code>string</code> data members are explicitly called, e.g.,
<code>name(mn)</code>. The initialization takes place <strong>before</strong> the code block of
<code>Person::Person()</code> (now empty) is executed. This construction, where member
initialization takes place before the code block itself is executed is called
<a name="an905"></a>
<em>member initialization</em>. Member initialization can be made explicit in
the <em>member initializer list</em>, that may appear after the parameter list,
between a colon (announcing the start of the member initializer list) and the
opening curly brace of the code block of the constructor.
<p>
Member initialization <em>always</em> occurs when objects are composed in classes:
if <em>no</em> constructors are mentioned in the member initializer list the
default constructors of the objects are called. Note that this only holds true
for <em>objects</em>. Data members of primitive data types are <em>not</em> initialized
automatically.
<p>
Member initialization can, however, also be used for primitive data members,
like <code>int</code> and <code>double</code>. The above example shows the initialization of the
data member <code>d_weight</code> from the parameter <code>weight</code>. Note that with member
initializers the data member could even have the same name as the constructor
parameter (although this is deprecated): with member initialization there is
no ambiguity and the first (left) identifier in, e.g., <code>weight(weight)</code> is
interpreted as the data member to be initialized, whereas the identifier
between parentheses is interpreted as the parameter.
<p>
When a class has multiple composed data members, all members can be
initialized using a `member initializer list': this list consists of the
constructors of all composed objects, separated by commas. The <em>order</em> in
<a name="an906"></a>
 which the objects are initialized is defined
by the order in which the members are defined in the class interface. If the
order of the initialization in the constructor differs from the order in the
class interface, the compiler complains, and reorders the initialization so as
to match the order of the class interface.
<p>
Member initializers should be used as often as possible: it can be downright
necessary to use them, and <em>not</em> using member initializers can result in
inefficient code: with objects always at least the default constructor is
called. So, in the following example, first the <code>string</code> members are
initialized to empty strings, whereafter these values are immediately
redefined to their intended values. Of course, the immediate initialization to
the intended values would have been more efficent.
        <pre>
    Person::Person(char const *name, char const *address,
                    char const *phone, size_t weight)
    {
        d_name = name;
        d_address = address;
        d_phone = phone;
        d_weight = weight;
    }
</pre>
    This method is not only inefficient, but even more: it may not work when
the composed object <a name="an907"></a>
 is declared as a <code>const</code>
object.  A data field like <code>birthday</code> is a good candidate for being
<code>const</code>, since a person's birthday usually doesn't change too much.
<p>
This means that when the definition of a <code>Person</code> is altered so as to
contain a <code>string const birthday</code> member, the implementation of the
constructor <code>Person::Person()</code> in which also the birthday must be
initialized, a member initializer <em>must</em> be used for <code>birthday</code>. Direct
assignment of the birthday would be illegal, since <code>birthday</code> is a <code>const</code>
data member. The next example illustrates the <code>const</code> data member
<a name="an908"></a>
 initialization:
        <pre>
    Person::Person(char const *name, char const *address,
                    char const *phone, char const *birthday,
                    size_t weight)
    :
        d_name(name),
        d_address(address),
        d_phone(phone),
        d_birthday(birthday),       // assume: string const d_birthday
        d_weight(weight)
    {}
</pre>
    Concluding, the rule of thumb is the following: when composition of
objects is used, the member initializer method is preferred to explicit
initialization of composed objects. This not only results in more efficient
code, but it also allows composed objects to be declared as <code>const</code> objects.
<p>
<a name="REFMEMBERS"></a><a name="l106"></a>
<h3>6.4.2: Composition and reference objects: reference member initializers</h3>
        <a name="classes/comref"></a>Apart from using member initializers to initialize composed objects (be they
<code>const</code> objects or not), there is another situation where member
initializers must be used. Consider the following situation.
<p>
A program uses an object of the class <code>Configfile</code>, defined in <code>main()</code>
to access the information in a configuration file. The configuration file
contains parameters of the program which may be set by changing the values in
the configuration file, rather than by supplying command line arguments.
<p>
Assume that another object that is used in the function <code>main()</code> is an
object of the class <code>Process</code>, doing `all the work'. What possibilities do
we have to tell the object of the class <code>Process</code> that an object of the
class <code>Configfile</code> exists?
    <ul>
    <li> The objects could have been declared as <em>global</em> objects. This
<em>is</em> a possibility, but not a very good one, since all the advantages of
local objects are lost.
    <li> The <code>Configfile</code> object may be passed to the <code>Process</code> object at
construction time. Bluntly passing an object (i.e., by value) might not
be a very good idea, since the object must be copied into the <code>Configfile</code>
parameter, and then a data member of the <code>Process</code> class can be used to make
the <code>Configfile</code> object accessible throughout the <code>Process</code> class. This
might involve yet another object-copying task, as in the following situation:
        <pre>
    Process::Process(Configfile conf)   // a copy from the caller
    {
        d_conf = conf;                  // copying to conf_member
    }
</pre>
    <li> The copy-instructions can be avoided if <em>pointers</em> to
the <code>Configfile</code> objects are used, as in:
        <pre>
    Process::Process(Configfile *conf)  // pointer to external object
    {
        d_conf = conf;                  // d_conf is a Configfile *
    }
</pre>
    This construction as such is ok, but forces us to use the `<code>-&gt;</code>' field
selector operator, rather than the `<code>.</code>' operator, which is (disputably)
awkward: conceptually one tends to think of the <code>Configfile</code> object as an
object, and not as a pointer to an object. In <strong>C</strong> this would probably have
been the preferred method, but in <strong>C++</strong> we can do better.
    <li> Rather than using value or pointer parameters, the <code>Configfile</code>
parameter could be defined as a <a name="an909"></a>
<em>reference parameter</em> to the <code>Process</code>
constructor. Next, we can define a <code>Config</code> reference data member in the
<code>class Process</code>. Using the reference variable effectively uses a pointer,
disguised as a variable.
    </ul>
    However, the following construction will <em>not</em> result in the
initialization of the <code>Configfile &amp;d_conf</code> reference data member:
        <pre>
    Process::Process(Configfile &amp;conf)
    {
        d_conf = conf;        // wrong: no assignment
    }
</pre>
    The statement <code>d_conf = conf</code> fails, because the compiler won't see
this as an initialization, but considers this an assignment of one
<code>Configfile</code> object (i.e., <code>conf</code>), to another (<code>d_conf</code>).  It does
so, because that's the normal interpretation: an assignment to a reference
variable is actually an assignment to the variable the reference variable
refers to. But to what variable does <code>d_conf</code> refer? To no variable, since
we haven't initialized <code>d_conf</code>.  After all, the whole purpose of the
statement <code>d_conf = conf</code> was to initialize <code>d_conf</code>....
<p>
So, how do we proceed when <code>d_conf</code> must be initialized? In this
situation we once again use the member initializer syntax. The following
example shows the correct way to initialize <code>d_conf</code>:
        <pre>
    Process::Process(Configfile &amp;conf)
    :
        d_conf(conf)      // initializing reference member
    {}
</pre>
    Note that this syntax must be used in all cases where reference data
members are used. If <code>d_ir</code> would be an <code>int</code> reference data member, a
construction like
        <pre>
    Process::Process(int &amp;ir)
    :
        d_ir(ir)
    {}
</pre>
    would have been called for.
<p>
<a name="MUTABLE"></a><a name="l107"></a>
<h2>6.5: The keyword `mutable'</h2>
    <a name="classes/mutable"></a>Earlier, in section <a href="cplusplus06.html#ConstFunctions">6.2</a>, the concepts of
<code>const</code> member functions and <code>const</code>
    <a name="an910"></a>

    objects were introduced.
<p>
<strong>C++</strong>, however, allows the construction of objects which are, in a sense,
neither <code>const</code> objects, nor <em>non-</em><code>const</code> objects. Data members which
are defined using the keyword <a name="an911"></a>
<code>mutable</code>, can be modified by <code>const</code> member
functions.
<p>
An example of a situation where <code>mutable</code> might come in handy is where a
<code>const</code> object needs to register the number of times it was used. The
following example illustrates this situation:
<p>
<pre>
#include &lt;string&gt;
#include &lt;iostream&gt;
#include &lt;memory&gt;


class Mutable
{
    std::string d_name;
    mutable int d_count;                // uses mutable keyword

    public:
        Mutable(std::string const &amp;name)
        :
            d_name(name),
            d_count(0)
        {}

        void called() const
        {
            std::cout &lt;&lt; "Calling " &lt;&lt; d_name &lt;&lt;
                                    " (attempt " &lt;&lt; ++d_count &lt;&lt; ")\n";
        }
};


int main()
{
    Mutable const x("Constant mutable object");

    for (int idx = 0; idx &lt; 4; idx++)
        x.called();                     // modify data of const object
}

/*
    Generated output:

    Calling Constant mutable object (attempt 1)
    Calling Constant mutable object (attempt 2)
    Calling Constant mutable object (attempt 3)
    Calling Constant mutable object (attempt 4)
*/
</pre>
<p>
The keyword <code>mutable</code> may also be useful in classes implementing, e.g.,
reference counting. Consider a class implementing reference counting for
textstrings. The object doing the reference counting might be a <code>const</code>
object, but the class may define a copy constructor. Since <code>const</code> objects
can't be modified, how would the copy constructor be able to increment the
reference count? Here the <code>mutable</code> keyword may profitably be used, as it
can be incremented and decremented, even though its object is a <code>const</code>
object.
<p>
The advantage of having a <code>mutable</code> keyword is that, in the end, the
programmer decides which data members can be modified and which data members
can't. But that might as well be a disadvantage: having the keyword
<code>mutable</code> around prevents us from making rigid assumptions about the
stability of <code>const</code> objects. Depending on the context, that may or may not
be a problem. In practice, <code>mutable</code> tends to be useful only for internal
bookkeeping purposes: accessors returning values of mutable data members might
return puzzling results to clients using these accessors with <code>const</code>
objects. In those situations, the nature of the returned value should clearly
be documented. As a <a name="an912"></a>
rule of thumb: do not use <code>mutable</code> unless there is a
very clear reason to divert from this rule.
<p>
<a name="CLASSHEADER"></a><a name="l108"></a>
<h2>6.6: Header file organization</h2>
    <a name="classes/headers"></a>In section <a href="cplusplus02.html#CHeaders">2.5.9</a> the requirements for header files when a <strong>C++</strong>
program also uses <strong>C</strong> functions were discussed.
<p>
When classes are used, there are more requirements for the organization of
<a name="an913"></a>
 header files. In this section these requirements
are covered.
<p>
First, the source files. With the exception of the occasional classless
function, source files should contain the code of member functions of classes.
With source files there are basically two approaches:
    <ul>
    <li> All required header files for a member function are included in each
individual source file.
    <li> All required header files for all member functions are included in the
class-headerfile, and each sourcefile of that class includes only the header
file of its class.
    </ul>
    The first alternative has the advantage of economy for the compiler: it
only needs to read the header files that are necessary for a particular source
file. It has the disadvantage that the program developer must include multiple
header files again and again in sourcefiles: it both takes time to type the
<code>include</code>-directives and to think about the header files which are needed in
a particular source file.
<p>
The second alternative has the advantage of economy for the program developer:
the header file of the class accumulates header files, so it tends to become
more and more generally useful. It has the disadvantage that the compiler
frequently has to read header files which aren't actually used by the function
defined in the source file.
<p>
With computers running faster and faster we think the second alternative is to
be preferred over the first alternative. So, as a starting point we suggest
that source files of a particular class <code>MyClass</code> are organized according to
the following example:
        <pre>
    #include &lt;myclass.h&gt;

    int MyClass::aMemberFunction()
    {}
</pre>
    There is only one <code>include</code>-directive. Note that the directive refers to
a header file in a directory mentioned in the <a name="an914"></a>
<code>INCLUDE</code>-file environment
variable. Local header files (using <code>#include "myclass.h"</code>) could be used
too, but that tends to complicate the organization of the class header file
itself somewhat.
<p>
If <a name="an915"></a>
name collisions with existing header files might occur it pays off
to have a subdirectory of one of the directories mentioned in the <code>INCLUDE</code>
environment variable (e.g., <code>/usr/local/include/myheaders/</code>).
<p>
If a class <code>MyClass</code> is developed there, create a subdirectory (or
subdirectory link) <code>myheaders</code> of one of the standard <code>INCLUDE</code>
directories to contain all header files of all classes that are developed as
part of the project. The <code>include</code>-directives will then be similar to
<code>#include &lt;myheaders/myclass.h&gt;</code>, and name collisions with other header
files are avoided.
<p>
The organization of the header file itself requires some attention. Consider
the following example, in which two classes <code>File</code> and <code>String</code> are
used.
<p>
Assume the <code>File</code> class has a member <code>gets(String &amp;destination)</code>, while
the class <code>String</code> has a member function <code>getLine(File &amp;file)</code>. The
(partial) header file for the <code>class String</code> is then:
        <pre>
    #ifndef _String_h_
    #define _String_h_

    #include &lt;project/file.h&gt;   // to know about a File

    class String
    {
        public:
            void getLine(File &amp;file);
    };
    #endif
</pre>
    However, a similar setup is required for the class <code>File</code>:
        <pre>
    #ifndef _File_h_
    #define _File_h_

    #include &lt;project/string.h&gt;   // to know about a String

    class File
    {
        public:
            void gets(String &amp;string);
    };
    #endif
</pre>
    Now we have created a problem. The compiler, trying to compile the source
file of the function <code>File::gets()</code> proceeds as follows:
    <ul>
    <li> The header file <code>project/file.h</code> is opened to be read;
    <li> <code>_File_h_</code> is defined
    <li> The header file <code>project/string.h</code> is opened to be read
    <li> <code>_String_h_</code> is defined
    <li> The header file <code>project/file.h</code> is (again) opened to be read
    <li> Apparently, <code>_File_h_</code> is already defined, so the remainder of
            <code>project/file.h</code> is skipped.
    <li> The interface of the class <code>String</code> is now parsed.
    <li> In the class interface a reference to a <code>File</code> object is
            encountered.
    <li> As the <code>class File</code> hasn't been parsed yet, a <code>File</code> is still
        an undefined type, and the compiler quits with an error.
    </ul>
    The solution for this problem is to use a <a name="an916"></a>
<em>forward class reference</em>
<em>before</em> the class interface, and to include the corresponding class header
file <em>after</em> the class interface. So we get:
        <pre>
    #ifndef _String_h_
    #define _String_h_

    class File;                 // forward reference

    class String
    {
        public:
            void getLine(File &amp;file);
    };

    #include &lt;project/file.h&gt;   // to know about a File

    #endif
</pre>
    A similar setup is required for the class <code>File</code>:
        <pre>
    #ifndef _File_h_
    #define _File_h_

    class String;               // forward reference

    class File
    {
        public:
            void gets(String &amp;string);
    };

    #include &lt;project/string.h&gt;   // to know about a String

    #endif
</pre>
    This works well in all situations where either references or pointers to
another classes are involved and with (non-inline) member functions having
    <a name="an917"></a>
class-type return values or <a name="an918"></a>
 parameters.
<p>
Note that this setup doesn't work with <a name="an919"></a>
composition, nor with inline
member functions. Assume the class <code>File</code> has a <em>composed</em> data member of
the class <code>String</code>. In that case, the class interface of the class <code>File</code>
<em>must</em> include the header file of the class <code>String</code> before the class
interface itself, because otherwise the compiler can't tell how big a <code>File</code>
object will be, as it doesn't know the size of a <code>String</code> object once the
interface of the <code>File</code> class is completed.
<p>
In cases where classes contain composed objects (or are derived from other
classes, see chapter <a href="cplusplus13.html#INHERITANCE">13</a>) the header files of the classes of the
composed objects must have been read <em>before</em> the class interface itself.
In such a case the <code>class File</code> might be defined as follows:
        <pre>
    #ifndef _File_h_
    #define _File_h_

    #include &lt;project/string.h&gt;     // to know about a String

    class File
    {
        String d_line;              // composition !

        public:
            void gets(String &amp;string);
    };
    #endif
</pre>
    Note that the class <code>String</code> can't have a <code>File</code> object as a composed
member: such a situation would result again in an undefined class while
compiling the sources of these classes.
<p>
All remaining header files (appearing below the class interface itself)
are required only because they are used by the class's source files.
<p>
This approach allows us to introduce yet another refinement:
    <ul>
    <li> Header files defining a class interface should <em>declare</em> what can
be declared before defining the class interface itself. So, classes that are
mentioned in a class interface  should be specified using
    <a name="an920"></a>
forward declarations <em>unless</em>
        <ul>
        <li> They are a <em>base class</em> of the current class (see chapter
<a href="cplusplus13.html#INHERITANCE">13</a>);
        <li> They are the class types of composed data members;
        <li> They are used in inline member functions.
        </ul>
    In particular: additional actual header files are <em>not</em> required for:
        <ul>
            <li> class-type return values of functions;
            <li> class-type value parameters of functions.
        </ul>
    Header files of classes of objects that are either composed or inherited
or that are used in inline functions, <em>must</em> be known to the compiler before
the interface of the current class starts.  The information in the header
file itself is protected by the <code>#ifndef ... #endif</code> construction introduced
in section <a href="cplusplus02.html#CHeaders">2.5.9</a>.
    <li> Program sources in which the class is used only need to include this
header file. <a name="an921"></a>
 <em>Lakos</em>, (2001) refines this process even
further. See his book <strong>Large-Scale <strong>C++</strong> Software Design</strong> for further
details. This header file should be made available in a well-known location,
such as a directory or subdirectory of the standard <a name="an922"></a>
<code>INCLUDE</code> path.
    <li> For the implementation of the member functions the class's header file
is required and usually other header files (like <code>#include &lt;string&gt;</code>) as
well. The class header file itself as well as these additional header files
should be included in a separate internal header file (for which the extension
<code>.ih</code> <a name="an923"></a>
 (`<a name="an924"></a>
internal header') is suggested).
<p>
The <code>.ih</code> file should be defined in the same directory as the source
files of the class, and has the following characteristics:
        <ul>
        <li> There is <em>no</em> need for a protective <code>#ifndef</code> .. <code>#endif</code>
shield, as the header file is never included by other header files.
        <li> The standard <code>.h</code> header file defining the class interface
is included.
        <li> The header files of all classes used  as forward references in
the standard <code>.h</code> header file are included.
        <li> Finally, all other header files that are required in the source
files of the class are included.
        </ul>
    An example of such a header file organization is:
        <ul>
        <li> First part, e.g., <code>/usr/local/include/myheaders/file.h</code>:
        <pre>
    #ifndef _File_h_
    #define _File_h_

    #include &lt;fstream&gt;      // for composed 'ifstream'

    class Buffer;           // forward reference

    class File              // class interface
    {
        ifstream d_instream;

        public:
            void gets(Buffer &amp;buffer);
    };
    #endif
</pre>
        <li> Second part, e.g., ~/myproject/file/file.ih, where all sources of
the class File are stored:
        <pre>
    #include &lt;myheaders/file.h&gt; // make the class File known

    #include &lt;buffer.h&gt;         // make Buffer known to File
    #include &lt;string&gt;           // used by members of the class
    #include &lt;sys/stat.h&gt;       // File.
</pre>
        </ul>
    </ul>
<p>
<a name="NAMESPACEHDR"></a><a name="l109"></a>
<h3>6.6.1: Using namespaces in header files</h3>
        <a name="classes/namespaces"></a>When entities from <a name="an925"></a>
 namespaces are used in <a name="an926"></a>
 header
files, in general  <a name="an927"></a>
<code>using</code> directives should not be used in these header
files if they are to be used as general header files declaring classes or
other entities from a <a name="an928"></a>
library. When the <code>using</code> directive is used in a
header file then users of such a header file are forced to accept and use the
declarations in all code that includes the particular header file.
<p>
For example, if in a namespace <code>special</code> an object <code>Inserter cout</code> is
declared, then <code>special::cout</code> is of course a different object than
<code>std::cout</code>. Now, if a class <code>Flaw</code> is constructed, in which the
constructor expects a reference to a <code>special::Inserter</code>, then the class
should be constructed as follows:
        <pre>
    class special::Inserter;

    class Flaw
    {
    public:
        Flaw(special::Inserter &amp;ins);
    };
</pre>
    Now the person designing the class <code>Flaw</code> may be in a <a name="an929"></a>
lazy mood, and
might get bored by continuously having to prefix <code>special::</code> before every
entity from that namespace. So, the following construction is used:
        <pre>
    using namespace special;

    class Inserter;

    class Flaw
    {
    public:
        Flaw(Inserter &amp;ins);
    };
</pre>
    This works fine, up to the point where somebody wants to include
<code>flaw.h</code> in other source files: because of the <code>using</code> directive, this
latter person is now by implication also <code>using namespace special</code>, which
could produce unwanted or unexpected effects:
        <pre>
    #include &lt;flaw.h&gt;
    #include &lt;iostream&gt;

    using std::cout;

    int main()
    {
        cout &lt;&lt; "starting" &lt;&lt; endl;     // doesn't compile
    }
</pre>
    The compiler is confronted with two interpretations for <code>cout</code>: first,
because of the <code>using</code> directive in the <code>flaw.h</code> header file, it considers
<code>cout</code> a <code>special::Extractor</code>, then, because of the <code>using</code> directive in
the user program, it considers <code>cout</code> a <code>std::ostream</code>. As compilers do,
when confronted with an ambiguity, an error is reported.
<p>
As a <a name="an930"></a>
rule of thumb, header files intented to be generally used should
not contain <code>using</code> declarations. This rule does not hold true
for header files which are included only by the sources of a class: here the
programmer is free to apply as many <code>using</code> declarations as desired, as
these directives never reach other sources.
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus05.html">Previous Chapter</a>
    <li> <a href="cplusplus07.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
